#!/usr/bin/env node

var Path = require("path");
var Url = require("url");

var proc = Path.basename(process.argv[1]);

var modules_failed = [];

var please_require = function(module) {
  try {
    return require(module);
  } catch(error) {
    console.error("%s: %s, %s", proc, error.name, error.message);
    modules_failed.push(module);
    return null;
  }
}

var Browser = please_require("zombie");
var htmlToText = please_require("html-to-text");

if(modules_failed.length !== 0) {
  console.log("%s: You probably need to run:", proc);
  modules_failed.forEach(function(module) {
    console.log("%s:  npm install %s", proc, module);
  });
  process.exit(2);
}

var zombie_opts = { debug: false };
var htt_opts = { wordwrap: (process.stdout.columns || 120) };

var showSection = function(sectionName, sectionHtml) {
    console.log("%s: ######## %s ########", proc, sectionName);
    var plainText = htmlToText.fromString(sectionHtml, htt_opts);
    console.log(plainText);
}

var jobs = process.argv.slice(2);

var return_code = 0;
var browser = null;
var check_cb = null;
var problem_cb = null;

var startBrowser = function() {
    if(browser) {
        browser.close();
    }
    var url = jobs.shift();
    if(url === undefined) {
        console.log("%s: complete", proc);
        process.exit(return_code);
        return;
    }
    var url_obj = Url.parse(url);
    if(!url_obj.protocol) {
        url_obj.protocol = "file";
        url = Url.format(url_obj);
    }
    console.log("%s: Loading %s ...", proc, url);
    browser = new Browser();
    browser.visit(url, zombie_opts, null).then(check_cb).fail(problem_cb);
};

problem_cb = function(error) {
    return_code = 1;
    console.warn("Test failed: ", error);
    startBrowser();
}

check_cb = function() {
    var done = false;
    var one_prob = function(err_obj) {
        console.warn("%s: %s, %s; %s", proc, err_obj.type,
                     err_obj.message, err_obj.data.error);
        return_code = 1;
        done = true;
    };
    (browser.errors || []).forEach(one_prob);
    (browser.document.errors || []).forEach(one_prob);
    var report = browser.html("#errorReport");
    if(report.match(/Test results/i)) {
        done = true;
        showSection("TEST RESULTS", report);
    }
    var timing = browser.html("#timing");
    if(timing) {
        showSection("TIMING", timing);
    }
    if(done) {
        startBrowser();
    } else {
        browser.wait().then(check_cb).fail(problem_cb);
    }
}

startBrowser();
